package com.m7788.screen;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.m7788.util.AppUtil;
import com.m7788.util.Constant;
import com.m7788.util.HttpService;
import com.m7788.util.ImageUpload;
import com.m7788.view.UmengBaseActivity;
import com.tool.utils.DataUtil;

public class LoginScreen extends UmengBaseActivity implements OnClickListener{
	private final int bannerDetailCode = 1;
	private EditText et_account;//账号
	private EditText et_password,et_password2;//密码
	private CheckBox savePass,autoLogin;//记住密码单选框
	private ProgressDialog progressDialog;
	private Bundle bundle;
	private String key="",account,userPass,userPass2;
	private Button btn_return,btn_login;
	private TextView btn_forget;
	private String url;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
        //LogoutUtil.getInstance().addActivity(this);
       //requestWindowFeature(Window.FEATURE_NO_TITLE);
        //setContentView(R.layout.index_screen);
     AppUtil.clearMemory(LoginScreen.this);
       //启动时清除缓存图片
     DataUtil.deleFileInFolder(ImageUpload.getInstance(LoginScreen.this).getFileDir());

		String url = getIntent().getStringExtra("url");
		Log.d("Chenguangxi","loginIn");
		startNextActivity(url);
        //bundle = getIntent().getExtras();
       // if(bundle!=null){
       // 	key = bundle.getString("key");
       // }
       // initView();
      //  initDBdata();
//        et_account.setText("lya091919");  
//        et_password.setText("091919"); 
//        et_password2.setText("091919"); 
    }
    
    @Override
    protected void onRestart() {
           super.onRestart();
           
//           if("true".equals(dbUtil.getRecord("LoginFlag"))){
//          		finish();
//           }
    }


    @Override
	protected void onPause() {
		super.onPause();
	}
	@Override
	protected void onResume() {
		super.onResume();
	}
    @Override
	protected void onDestroy() {
		super.onDestroy();
	}
    /**
     * 
     * 方法名：initView 
     * 功能：初始化各个控件，并且添加监听
     * 参数：
     * 创建人：huanghsh  
     * 创建时间：2012-6-19
     */
    private void initView(){
    	et_account = (EditText)findViewById(R.id.ls_et_account);
        et_password = (EditText)findViewById(R.id.ls_et_password);
        et_password2 = (EditText)findViewById(R.id.ls_et_password2);
        savePass = (CheckBox)findViewById(R.id.ls_ck_save_pass);
        savePass.setOnCheckedChangeListener(cbListener); 
        
        autoLogin = (CheckBox)findViewById(R.id.ls_ck_auto_login);
        autoLogin.setOnCheckedChangeListener(autoListener); 
        
        
        
        btn_return =(Button)findViewById(R.id.ls_btn_return);
        btn_return.setOnClickListener(this);
        btn_login = (Button)findViewById(R.id.ls_btn_login);
        btn_login.setOnClickListener(this);
        
        btn_forget=(TextView)findViewById(R.id.ls_btn_forget);
        btn_forget.setClickable(true);
        btn_forget.setOnClickListener(this);
		
        
    }
    
    
    /**
     * 
     * 方法名：initDBdata 
     * 功能：初始化initDBdata，读取用户账号和密码
     * 参数：
     * 创建人：huanghsh  
     * 创建时间：2012-6-19
     */
    private void initDBdata(){
//    	dbUtil.updateOrAddRecord("token","");
    	String tokenStr = AppUtil.getToken(LoginScreen.this);
    	if(!"changeUser".equals(key)){
    		et_account.setText(AppUtil.getRecord(LoginScreen.this,"account"));
    	}
    	
    	
    	if("true".equals(AppUtil.getRecord(LoginScreen.this,"savePass"))&&!"changeUser".equals(key)){
    		et_password.setText(AppUtil.getRecord(LoginScreen.this,"password"));
    		et_password2.setText(AppUtil.getRecord(LoginScreen.this,"password2"));
    		savePass.setChecked(true);
    	}
    	
    	if("true".equals(AppUtil.getRecord(LoginScreen.this,"autoLogin"))&&!"changeUser".equals(key)){
    		 autoLogin.setChecked(true);
    		 account =  AppUtil.getRecord(LoginScreen.this,"account");
    		 userPass = AppUtil.getRecord(LoginScreen.this,"password");
    		 userPass2 = AppUtil.getRecord(LoginScreen.this,"password2");
    		 if(account.length()>0&&userPass.length()>0){
//    		    LoginAsyncTask loginAsyncTask = new LoginAsyncTask();
// 	    		loginAsyncTask.execute(account,userPass,LoginScreen.this);
// 	    		progressDialog = ProgressDialog.show
// 				(LoginScreen.this, 
// 						null, 
// 						"登录中...", 
// 						true, true);
    		 }else{
    			 DataUtil.Alert(LoginScreen.this, "账户或者密码为空，无法自动登录。");
    		 }
    		
    	}
    	
    	if(!"changeUser".equals(key)&&tokenStr.length()>1){
    		startNextActivity("");
    	}
    }
    
    
    
    public void onClick(View v){
		switch(v.getId()){
    	case R.id.ls_btn_login:
			
    		login();    
    		break;
    	case R.id.ls_btn_forget:
    		Toast.makeText(this, "该功能暂未开放", Toast.LENGTH_LONG).show();
            break;
    	case  R.id.ls_btn_return:
    		Intent intent =new Intent(LoginScreen.this,RegisterScreen.class);
    		startActivity(intent);			
    		break;
    		
    	}
    }
    
    /**
     * 
     * 方法名：login 
     * 功能：登录验证
     * 参数：
     * 创建人：huanghsh  
     * 创建时间：2012-6-19
     */
    private void login(){
    	 account = et_account.getText().toString().trim();
		 userPass = et_password.getText().toString().trim();
		 userPass2 = et_password2.getText().toString().trim();
		 AppUtil.saveRecord(LoginScreen.this,"account", account);
//		 startNextActivity();
		if(DataUtil.isConnectNet(LoginScreen.this)){
			if(account.length()>0&&userPass.length()>0&&userPass2.length()>0){
				
	    		LoginAsyncTask loginAsyncTask = new LoginAsyncTask();
	    		loginAsyncTask.execute();
	    		progressDialog = ProgressDialog.show
				(LoginScreen.this, 
						null, 
						"登录中...", 
						true, true);
			}else{
				DataUtil.Alert(LoginScreen.this,"请输入用户名和密码");
			}
		}else{
			DataUtil.Alert(LoginScreen.this,"请先启用网络");
		}
    }
    
    
    
    
    
    /**
     * 单选按钮的触发事件，选择则保存账号及密码
     */
    private CheckBox.OnCheckedChangeListener cbListener =    
        new CheckBox.OnCheckedChangeListener(){   
    	@Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {     
                if(savePass.isChecked()){
                	
                }else{ 
					AppUtil.saveRecord(LoginScreen.this,"savePass","false");
                }   
            }
    }; 
    
    private CheckBox.OnCheckedChangeListener autoListener =    
        new CheckBox.OnCheckedChangeListener(){   
    	@Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {     
                if(autoLogin.isChecked()){
                	
                }else{
					AppUtil.saveRecord(LoginScreen.this,"autoLogin","false");
                }   
            }
    }; 

    
//    @Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		// 如果是返回键,直接返回到桌面  	
//		if(keyCode == KeyEvent.KEYCODE_BACK){
//			LogoutApp.getInstance().exit(this);
//		}
//		return true;
//	}
          
	private class LoginAsyncTask extends AsyncTask<Object, Object, Object> {
		
		@Override
		protected void onPostExecute(Object result) {
			progressDialog.dismiss();
			if(result!=null&&result.toString().length()>0){
				String json = result.toString();
//				Log.e("login", json);
				  try {
					String ret = new JSONObject(json).getString("ret");
					if("0".equals(ret)){
						DataUtil.showShortToast(LoginScreen.this, "数据异常");
					} else if("1".equals(ret)){
						String code = new JSONObject(json).getString("result");
						String token = new JSONObject(json).getString("token");
						String desc = new JSONObject(json).getString("desc");
						String sid = new JSONObject(json).getString("s_id");
						String pid = new JSONObject(json).getString("p_id");
						String shopname = new JSONObject(json).getString("shop_user");
						String uploadUrl = new JSONObject(json).getString("url");
						if("1".equals(code)){
							SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoginScreen.this);
							SharedPreferences.Editor editor = mSharedPreferences.edit();
							editor.putString("token",token);
							editor.commit();
							AppUtil.saveRecord(LoginScreen.this,Constant.sid,sid);
							AppUtil.saveRecord(LoginScreen.this,Constant.Tpid,pid); //本地拍照上传 传到此文件夹
							AppUtil.saveRecord(LoginScreen.this,Constant.shopName,shopname);
							AppUtil.saveRecord(LoginScreen.this,Constant.URL_UPLOAD,uploadUrl);
							
//							Log.e("token", token);
							startNextActivity("");
						}else{
							DataUtil.showShortToast(LoginScreen.this, desc);
						}
						
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}	
			}else{
				DataUtil.showShortToast(LoginScreen.this, "登录失败");
			}
			super.onPostExecute(result);			
		}

		@Override
		protected Object doInBackground(Object... params) {
			return HttpService.getInstance(LoginScreen.this.getApplicationContext()).login(account,userPass,userPass2);
		}
	}


	//
	private void startNextActivity(String url){
		Intent intent =new Intent(LoginScreen.this,IndexScreen.class);
		intent.putExtra("url",url);
//		Intent intent =new Intent(LoginScreen.this,DirectoryScreen.class);
		startActivity(intent);
		overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
		finish();
	}
	
  
}